import 'dart:async';

import 'package:flutter/material.dart';

class BannerWiget extends StatefulWidget {
  final List<String> list;
  final Duration loopDuration;
  BannerWiget(
      {@required this.list, this.loopDuration = const Duration(seconds: 3)});
  @override
  _BannerWigetState createState() => _BannerWigetState();
}

class _BannerWigetState extends State<BannerWiget> {
  int _total;
  int _current = 1;
  Timer _timer;
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _total = widget.list.length;
    setState(() {});
    _pageController = new PageController(initialPage: widget.list.length);
    startLoopFunction();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (_timer.isActive) {
      _timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 200,
      child: Stack(
        children: [
          // 第一层 构建banner
          buildBanner(),
          // 第二层 构建dot
          buildDot(),
        ],
      ),
    );
  }

  Widget buildDot() {
    return Positioned(
      bottom: 20,
      right: 20,
      child: Container(
        alignment: Alignment.center,
        height: 20,
        width: 40,
        decoration: BoxDecoration(
          color: Colors.grey.withOpacity(0.5),
          borderRadius: BorderRadius.all(Radius.circular(10)),
        ),
        child: Text("$_current/$_total", style: TextStyle(color: Colors.white)),
      ),
    );
  }

  Widget buildBanner() {
    return Positioned.fill(
      child: PageView.builder(
        controller: _pageController,
        itemCount: widget.list.length,
        onPageChanged: (value) {
          setState(() {
            _current = value + 1;
          });
        },
        itemBuilder: (BuildContext context, int index) {
          String banner = widget.list[index];
          return Image.asset(banner, fit: BoxFit.fill);
        },
      ),
    );
  }

  void startLoopFunction() {
    _timer = Timer.periodic(widget.loopDuration, (timer) {
      _pageController.nextPage(
          duration: Duration(milliseconds: 200), curve: Curves.linear);
    });
  }
}
